'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class LoginController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
    }
    //登录
    async login() {
        const { ctx } = this
        let { username, password } = ctx.request.body
        const login = await this.app.mysql.get('login', { username, password });
        if (login) {
            ctx.body = {
                code: 200,
                msg: '登录成功',
                token: jwt.sign(username, '1907A')
            }
        } else {
            ctx.body = {
                code: 403,
                msg: "登录失败"
            }
        }
    }
    //用户信息
    async getUserInfo() {
        const { ctx } = this
        const { authorization } = ctx.request.headers
        let username = ''
        try {
            username = jwt.verify(authorization, '1907A')
        } catch (error) {
            console.log(error);
        }
        console.log(username);
        const userInfo = await this.app.mysql.get('login', { username })
        console.log(userInfo);
        ctx.body = {
            code: 200,
            data: userInfo
        }
    }
    //注册
    async SigIn() {
        const { ctx } = this
        let { username, password, name, img = '', auth = '' } = ctx.request.body
        const SigIn = await this.app.mysql.get('login', { username });
        if (!SigIn) {
            const result = await this.app.mysql.insert('login', { username, password, name, img, auth });
            if (result.affectedRows) {
                ctx.body = {
                    code: 200,
                    msg: '注册成功'
                }
            } else {
                ctx.service = 403
                ctx.body = {
                    code: 403,
                    msg: '注册失败'
                }
            }
        } else {
            ctx.service = 403
            ctx.body = {
                code: 403,
                msg: '账号已存在'
            }
        }
    }
}

module.exports = LoginController;
